package com.xiejun.netty;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 使用管道模式的服务端示例
 */
public class PipelineServer {
    
    public static void main(String[] args) {
        try {
            // 创建管道并添加处理器
            ChannelPipeline pipeline = new ChannelPipeline();
            pipeline.addLast(new LoggingHandler())
                    .addLast(new EchoServerHandler());
            
            // 启动服务端
            new EnhancedSimpleNettyServer(8082, pipeline).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 日志处理器
     */
    static class LoggingHandler implements ChannelHandler {
        
        @Override
        public void channelRead(SocketChannel channel, ByteBuffer buffer) throws IOException {
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            String message = new String(data);
            System.out.println("[LOG] Received message: " + message);
        }
        
        @Override
        public void channelConnected(SocketChannel channel) throws IOException {
            System.out.println("[LOG] Client connected: " + channel.getRemoteAddress());
        }
        
        @Override
        public void channelDisconnected(SocketChannel channel) throws IOException {
            System.out.println("[LOG] Client disconnected: " + channel.getRemoteAddress());
        }
    }
}